package leetbook.array;

import java.util.ArrayList;
import java.util.Arrays;

class Solution2 {

    //nums = [1,2,3,4,5,6,7], k = 3
    //输出: [5,6,7,1,2,3,4]

    public static void main(String[] args) {
        int[] nums = new int[]{1,2,3,4,5,6,7};
        int k = 3;
        new Solution2().rotate(nums,k);
        System.out.println(Arrays.asList(nums));
    }

    public void rotate1(int[] nums, int k) {
        //+k取模
        int n = nums.length;
        int[] temp = new int[n];
        for (int i = 0; i < n; i++) {
            int idx = (i+k)%n;
            temp[idx] = nums[i];
        }
        System.arraycopy(temp,0,nums,0,n);
    }

    public void rotate(int[] nums, int k) {
        //原地置换，k%=n，
        //每次把0...n-2子数组向右移动1位，被移出的最右端数字到最左边
        //重复上一步k次
        int n = nums.length;
        k = k % n;
        for (int i = 0; i < k; i++) {
            //先把最右边的拿出来
            int temp = nums[n-1];
            //0...n-2子数组右移
            for (int j = n-2; j >= 0; j--) {
                nums[j+1] = nums[j];
            }
            //把移出的放到左边
            nums[0] = temp;
        }
    }
}
